package com.itlaobing.mvc.dao;

import com.itlaobing.mvc.entity.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

@Repository
public class EmployeeDao {

    @Autowired
    private HibernateTemplate hibernateTemplate ;

    public int save(Employee emp) {
        Integer id = (Integer) hibernateTemplate.save( emp );
        return id ;
    }

    public int remove(Integer id) {
        Employee e = new Employee();
        e.setId( id );
        //Employee e = hibernateTemplate.load( Employee.class , id );
        hibernateTemplate.delete(  e );
        return 0;
    }

    public int update(Employee emp) {
        hibernateTemplate.update( emp );
        return 0;
    }

    public Employee find(Integer id) {
        return hibernateTemplate.get( Employee.class , id );
    }

    public List<Employee> findAll() {
        return hibernateTemplate.loadAll( Employee.class );
    }

    public List<Employee> list(String name) { // 了解用 Hibernate 执行 HQL 语句
        SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
        Session session = sessionFactory.openSession();
        // HQL : Hibernate Query Language
        String hql = "FROM Employee WHERE name LIKE :nameLike ORDER BY id" ;
        // 创建用来执行HQL语句的 查询器
        Query<Employee> query = session.createQuery( hql , Employee.class );
        // 在执行查询之前可以设置参数占位符的参数值
        query.setParameter( "nameLike" , "%" + name + "%" );
        // 调用 Query 的 list 方法 可以执行查询
        List<Employee> list = query.list() ;
        session.close();
        return list ;
    }

    public Integer nextId() { // 了解使用 Hibernate 执行 原生SQL 语句
        Integer id = null ;
        SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
        Session session = sessionFactory.openSession();
        String sql = "SELECT NVL( max(id) , 0 ) + 1 FROM t_employees" ;
        // 执行原生SQL语句
        NativeQuery nativeQuery = session.createNativeQuery( sql );
        Object value = nativeQuery.uniqueResult() ;
        if( value instanceof BigDecimal) { // Oracle返回的是 BigDecimal
            BigDecimal bd = (BigDecimal) value ;
            id = bd.intValue() ;
        }
        return id;
    }

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

}
